package com.qx.cn.controller;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qx.cn.model.OrgInfo;
import com.qx.cn.model.SendDate;
import com.qx.cn.model.SendTime;
import com.qx.cn.model.User;
import com.qx.cn.model.WorkReport;
import com.qx.cn.model.WorkReportItem;
import com.qx.cn.model.WorkSendGroup;
import com.qx.cn.service.OrgInfoService;
import com.qx.cn.service.SendDateService;
import com.qx.cn.service.SendEmailService;
import com.qx.cn.service.SendTimeService;
import com.qx.cn.service.WorkReportItemService;
import com.qx.cn.service.WorkReportService;
import com.qx.cn.service.WorkSendGroupService;
import com.qx.cn.tool.DateForm;

@Controller
@RequestMapping("/workReport")
public class WorkReportController
{
    @Autowired
    HttpServletRequest request;
    
    @Autowired
    private OrgInfoService orgInfoService;
    
    @Autowired
    private SendDateService sendDateService;
    
    @Autowired
    private SendTimeService sendTimeService;
    
    @Autowired
    private WorkReportService workReportService;
    
    @Autowired
    private WorkReportItemService workReportItemService;
    
    @Autowired
    private WorkSendGroupService workSendGroupService;
    
    @Autowired
    private SendEmailService seService;
    
    public String workReportForm()
    {
        return "workReportForm";
    }
    
    @ResponseBody
    @RequestMapping(value = "queryWorkReportByPage")
    public JSONObject queryWorkReportByPage(String workReportName, int page, int rows)
        throws ParseException
    {
        User user = (User)request.getSession().getAttribute("user");
        WorkReport workReport = new WorkReport();
        workReport.setWorkReportName(workReportName);
        workReport.setUserId(Integer.valueOf(user.getUserId().intValue()));
        workReport.setType("day");
        List results = workReportService.queryWorkReportByPage(workReport, page, rows);
        JSONArray arrJson = new JSONArray();
        if (!results.isEmpty())
        {
            for (int i = 0; i < results.size(); i++)
            {
                Object[] row = (Object[])results.get(i);
                JSONObject json = new JSONObject();
                json.put("id", row[0]);
                json.put("workReportName", row[1]);
                json.put("createTime", row[2]);
                if ((String)row[2] != null)
                {
                    String cdateStr = row[2].toString().substring(0, 10);
                    json.put("sendTime", DateForm.dateToXingQi(cdateStr));
                }
                json.put("userId", row[4]);
                String nowMinDate = DateForm.SimpleDate(new Date()) + " 00:00:00";
                boolean minFlag = DateForm.StrToDateTime(nowMinDate).after(DateForm.StrToDateTime((String)row[2]));
                if (minFlag)
                {
                    json.put("status", "<span style='font-weight:700;color:#00CD00;'>已发送<span>");
                }
                else
                {
                    List<SendTime> sendTimes = sendTimeService.queryAllTimeToShow();
                    if (!sendTimes.isEmpty())
                    {
                        String eTimeStr = DateForm.SimpleDate(new Date()) + " " + ((SendTime)sendTimes.get(0)).getEndTime() + ":00";
                        boolean nMFlag = new Date().after(DateForm.StrToDateTime(eTimeStr));
                        if (nMFlag)
                        {
                            json.put("status", "<span style='font-weight:700;color:#00CD00;'>已发送<span>");
                        }
                        else
                        {
                            json.put("status", "<span style='font-weight:700;color:red;'>已提交<span>");
                        }
                    }
                    else
                    {
                        json.put("status", "<span style='font-weight:700;'>暂无<span>");
                    }
                }
                List<WorkReportItem> wReportItems = workReportItemService.queryWorkReportItems((String)row[7]);
                json.put("itemNum", Integer.valueOf(wReportItems.size()));
                Float sumTime = Float.valueOf(0.0F);
                for (WorkReportItem wr : wReportItems)
                {
                    if ((wr.getWorkTime() == null) || ("".equals(wr.getWorkTime())))
                    {
                        sumTime = Float.valueOf(sumTime.floatValue() + 0.0F);
                    }
                    else
                    {
                        sumTime = Float.valueOf(sumTime.floatValue() + Float.valueOf(wr.getWorkTime()).floatValue());
                    }
                }
                json.put("sumTime", sumTime);
                json.put("memo", row[6]);
                json.put("wrCode", row[7]);
                arrJson.add(json);
            }
        }
        JSONObject object = new JSONObject();
        object.put("total", Integer.valueOf(workReportService.queryAllWorkReports(workReport).size()));
        object.put("rows", arrJson);
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "lookWorkReport")
    public JSONObject lookWorkReport(Integer id)
    {
        WorkReport workReport = workReportService.loadWorkReportById(id);
        List<WorkReportItem> workReportItems = workReportItemService.queryWorkReportItems(workReport.getReportCode());
        JSONArray arrJson = new JSONArray();
        JSONObject object = new JSONObject();
        for (WorkReportItem workReportItem : workReportItems)
        {
            JSONObject json = new JSONObject();
            json.put("content", workReportItem.getContent());
            if (StringUtils.isNotEmpty(workReportItem.getWorkTime()))
            {
                json.put("workTime", workReportItem.getWorkTime());
            }
            json.put("remarks", StringUtils.trimToEmpty(workReportItem.getRemarks()));
            arrJson.add(json);
        }
        object.put("result", 1);
        object.put("datas", arrJson);
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "lookALLworkReportByDate")
    public JSONObject lookALLworkReportByDate(String startDate, String endDate)
    {
        User user = (User)request.getSession().getAttribute("user");
        StringBuffer stbuffer = new StringBuffer();
        List<WorkReport> workReports = workReportService.queryAllWorkReportsByDate(startDate, endDate, user, "day");
        if (workReports.size() > 0)
        {
            for (WorkReport workReport : workReports)
            {
                List<WorkReportItem> workReportItems = workReportItemService.queryWorkReportItems(workReport.getReportCode());
                stbuffer.append("<tr><td style='font-size:15px;font-weight:700'>姓名:" + user.getUserName() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名称:" + workReport.getWorkReportName()
                    + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;上交时间:" + workReport.getCreateTime() + "</td></tr>");
                stbuffer.append("<tr><td colspan='4'><table border='1' cellpadding='10'>");
                stbuffer.append(
                    "<tr style='background-color:#E8E8E8;'><th style='width:80px;'>序号</th><th style='width:500px;'>内容</th><th style='width:200px;'>时间（小时） </th><th style='width:200px;'>备注</th></tr>");
                for (int z = 0; z < workReportItems.size(); z++)
                {
                    WorkReportItem item = (WorkReportItem)workReportItems.get(z);
                    stbuffer.append("<tr><td align='center'>" + (z + 1) + "</td><td>" + item.getContent() + "</td><td align='center'>" + item.getWorkTime() + "</td><td align='center'>"
                        + StringUtils.trimToEmpty(item.getRemarks()) + "</td></tr>");
                }
                stbuffer.append("</td></tr></table>");
                stbuffer.append("<tr><td>&nbsp;</td></tr>");
            }
        }
        else
        {
            stbuffer.append("<tr><td align='center'><br/><br/><span style='color:red;'>无相关信息</span></td></tr>");
        }
        JSONObject object = new JSONObject();
        object.put("result", 1);
        object.put("content", stbuffer.toString());
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "saveWorkReport")
    public JSONObject saveWorkReport(Integer id, String wrCode)
    {
        // 更新日报汇总数据
        List<WorkSendGroup> workSendGroups = (List<WorkSendGroup>)seService.queryWorkSendGroup();
        if (!workSendGroups.isEmpty())
        {
            Date now = new Date();
            if (seService.checkIsSendDate(DateForm.SimpleDate(now)) && seService.notSend(DateForm.SimpleDate(now))) // 判断当天是否需要发日报
            {
                SendDate sysSendDate = seService.queryBySendDate(DateForm.SimpleDate(now));
                List<SendTime> sendTimes = seService.querySendTimes();
                if (!sendTimes.isEmpty())
                {
                    for (WorkSendGroup wGroup2 : workSendGroups)
                    {
                        if (wGroup2.getTimeTip() == 1 && StringUtils.isNotEmpty(wGroup2.getSenderIds()))
                        {
                            String[] wGroups = wGroup2.getSenderIds().split(",");
                            for (int i = 0; i < wGroups.length; i++)
                            {
                                seService.insertManageWorkReport(Integer.valueOf(wGroups[i]), wGroup2.getWorkerIds(), wGroup2.getGroupName(), sysSendDate.getType());
                            }
                        }
                    }
                }
            }
        }
        User user = (User)request.getSession().getAttribute("user");
        boolean flag = false;
        String msg = "";
        if (id != null)
        {
            WorkReport workReport = workReportService.loadWorkReportById(id);
            List<WorkReportItem> workReportItems = workReportItemService.queryWorkReportItems(workReport.getReportCode());
            if (!workReportItems.isEmpty())
            {
                WorkReport upWorkReport = workReportService.loadWorkReportById(id.intValue());
                upWorkReport.setWorkReportName(DateForm.SimpleDate(new Date()) + "日报");
                flag = workReportService.saveWorkReport(upWorkReport);
            }
            else
            {
                flag = false;
                msg = "请添加或者保存日报项的内容之后,再保存日报";
            }
        }
        else
        {
            List<WorkReportItem> workReportItems = workReportItemService.queryWorkReportItems(wrCode);
            if (!workReportItems.isEmpty())
            {
                WorkReport workReport = new WorkReport();
                workReport.setWorkReportName(DateForm.SimpleDate(new Date()) + "日报");
                workReport.setCreateTime(DateForm.SimpleDateTime(new Date()));
                workReport.setUserId(Integer.valueOf(user.getUserId().intValue()));
                workReport.setUserName(user.getUserName());
                OrgInfo orgInfo = orgInfoService.loadOrgByCode(user.getOrgCode());
                if (orgInfo != null)
                {
                    workReport.setOrgName(orgInfo.getOrgName());
                }
                else
                {
                    workReport.setOrgName("");
                }
                workReport.setPosition(user.getPositionName());
                workReport.setReportCode(wrCode);
                workReport.setType("day");
                flag = workReportService.saveWorkReport(workReport);
            }
            else
            {
                flag = false;
                msg = "请添加或者保存日报项的内容之后,再保存日报";
            }
        }
        JSONObject object = new JSONObject();
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "保存日报内容成功!");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", msg);
        }
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "deleteWorkReport")
    public JSONObject deleteWorkReport(Integer id)
    {
        WorkReport workReport = workReportService.loadWorkReportById(id.intValue());
        workReportItemService.deleteWorkItemByCode(workReport.getReportCode());
        boolean flag = workReportService.deleteWorkReport(id.intValue());
        JSONObject object = new JSONObject();
        if (flag)
        {
            object.put("result", 1);
            object.put("errorMsg", "删除发送组成功");
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", "删除发送组失败");
        }
        return object;
    }
    
    /**
     * 判断提交报告情况
     * 
     * @return
     * @throws ParseException
     * @see [类、类#方法、类#成员]
     */
    @ResponseBody
    @RequestMapping(value = "checkSendTime")
    public JSONObject checkSendTime()
        throws ParseException
    {
        boolean needFlag = false;
        String errorMsg = "";
        User user = (User)request.getSession().getAttribute("user");
        boolean notSendFlag = workReportService.queryCheckIsWorkReports(DateForm.SimpleDate(new Date()), user.getUserId(), "day");
        if (notSendFlag)
        {
            List<WorkSendGroup> workSendGroups = workSendGroupService.queryIsNotUserByUserId(user.getUserId());
            if (workSendGroups.size() > 0)
            {
                SendDate sendDate = sendDateService.queryAllSendDateByDate(DateForm.SimpleDate(new Date()), "day");
                if (sendDate != null)
                {
                    needFlag = true;
                }
                else
                {
                    needFlag = false;
                    errorMsg = "<span style='font-size:15px;'>今天不需要上交日报!</span>";
                }
            }
            else
            {
                needFlag = false;
                errorMsg = "<span style='font-size:15px;'>今天你不需要上交日报!</span>";
            }
        }
        else
        {
            needFlag = false;
            errorMsg = "<span style='font-size:15px;'>你已经添加当天的日报，不需重复添加!</span>";
        }
        if (needFlag)
        {
            List<SendTime> sendTimes = sendTimeService.queryAllTimeToShow();
            if (!sendTimes.isEmpty())
            {
                String sTimeStr = DateForm.SimpleDate(new Date()) + " " + sendTimes.get(0).getStartTime() + ":00";
                String eTimeStr = DateForm.SimpleDate(new Date()) + " " + sendTimes.get(0).getEndTime() + ":00";
                boolean tFlag = new Date().before(DateForm.StrToDateTime(sTimeStr));
                if (tFlag)
                {
                    needFlag = false;
                    errorMsg = "<span style='font-size:15px;'>还没有到日报允许上交时间,请在首页查看相关上交时间再添加!</span>";
                }
                else
                {
                    boolean etFlag = new Date().after(DateForm.StrToDateTime(eTimeStr));
                    if (etFlag)
                    {
                        needFlag = false;
                        errorMsg = "<span style='font-size:15px;'>已经过了截止发送时间,请自行发给相关负责人!</span>";
                    }
                }
            }
        }
        JSONObject object = new JSONObject();
        if (needFlag)
        {
            object.put("result", 1);
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", errorMsg);
        }
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "checkSendTimeToDel")
    public JSONObject checkSendTimeToDel(String createTime)
        throws ParseException
    {
        boolean flag = false;
        String errorMsg = "";
        String nowMinDate = DateForm.SimpleDate(new Date()) + " 00:00:00";
        boolean minFlag = DateForm.StrToDateTime(nowMinDate).after(DateForm.StrToDateTime(createTime));
        if (minFlag)
        {
            flag = false;
            errorMsg = "<span style='font-size:15px;'>该日报已经发送,不可删除!</span>";
        }
        else
        {
            List<SendTime> sendTimes = sendTimeService.queryAllTimeToShow();
            if (!sendTimes.isEmpty())
            {
                String eTimeStr = DateForm.SimpleDate(new Date()) + " " + sendTimes.get(0).getEndTime() + ":00";
                boolean nMFlag = new Date().after(DateForm.StrToDateTime(eTimeStr));
                if (nMFlag)
                {
                    flag = false;
                    errorMsg = "<span style='font-size:15px;'>该日报已经发送,不可删除!</span>";
                }
                else
                {
                    flag = true;
                }
            }
            else
            {
                errorMsg = "<span style='font-size:15px;'>还没有设置日报发送时间!</span>";
            }
        }
        JSONObject object = new JSONObject();
        if (flag)
        {
            object.put("result", 1);
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", errorMsg);
        }
        return object;
    }
    
    @ResponseBody
    @RequestMapping(value = "checkSendTimeToUpdate")
    public JSONObject checkSendTimeToUpdate(String createTime)
        throws ParseException
    {
        boolean flag = false;
        String errorMsg = "";
        String nowMinDate = DateForm.SimpleDate(new Date()) + " 00:00:00";
        boolean minFlag = DateForm.StrToDateTime(nowMinDate).after(DateForm.StrToDateTime(createTime));
        if (minFlag)
        {
            flag = false;
            errorMsg = "<span style='font-size:15px;'>该日报已经发送,不可修改!</span>";
        }
        else
        {
            List<SendTime> sendTimes = sendTimeService.queryAllTimeToShow();
            if (!sendTimes.isEmpty())
            {
                String eTimeStr = DateForm.SimpleDate(new Date()) + " " + sendTimes.get(0).getEndTime() + ":00";
                boolean nMFlag = new Date().after(DateForm.StrToDateTime(eTimeStr));
                if (nMFlag)
                {
                    flag = false;
                    errorMsg = "<span style='font-size:15px;'>该日报已经发送,不可修改!</span>";
                }
                else
                {
                    flag = true;
                }
            }
            else
            {
                errorMsg = "<span style='font-size:15px;'>还没有设置日报发送时间!</span>";
            }
        }
        JSONObject object = new JSONObject();
        if (flag)
        {
            object.put("result", 1);
        }
        else
        {
            object.put("result", 2);
            object.put("errorMsg", errorMsg);
        }
        return object;
    }
}